import 'dart:developer';

import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/pages/main/ab_main_tab_page.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_const_url.dart';
import 'package:ceramics/util/ab_init_db.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/util/ab_log_util.dart';
import 'package:ceramics/util/ab_uuid.dart';
import 'package:ceramics/widgets/ab_webview_page.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../widgets/ab_elevate_button.dart';
import 'ab_agree_dialog.dart';

class ABLoginPage extends StatefulWidget {
  const ABLoginPage({super.key});

  @override
  State<ABLoginPage> createState() => _ABLoginPageState();
}

class _ABLoginPageState extends State<ABLoginPage> {
  bool _selected = false;
  String _appleToken = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        extendBody: true,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          systemOverlayStyle: SystemUiOverlayStyle.dark,
        ),
        body: Container(
          width: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('images/ceramics_39.webp'),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Image.asset('images/logo.webp', width: 100).borderRadius(10),
              const SizedBox(height: 90),
              _buildAppleLogin().maxWidth(Get.width - 80),
              const SizedBox(height: 20),
              _buildFastLogin(),
              const SizedBox(height: 50),
              _buildBottomTP(),
              const SizedBox(height: 50)
            ],
          ),
        ));
  }

  _login1() async {
    if (!_selected) {
      var result = await Get.dialog(const ABAgreeDialog());
      if (result == true) {
        setState(() {
          _selected = true;
        });
        _login2();
      }
    } else {
      _login2();
    }
  }

  _login2() async {
    var token = _appleToken.isEmpty ? (await getUUID()) : _appleToken;
    var type = _appleToken.isEmpty ? 4 : 3;
    var res = await api.oauth(type, token);
    ABSingleton.updateOAuth(res);
    LogPvManger.stat(page: 'loginsuccess');
    loading();
    await replaceUser();
    dismissLoading();
    Get.off(() => const ABMainTabPage());
  }

  _signApple() async {
    LogPvManger.stat(page: 'applelogin');
    if (!_selected) {
      var result = await Get.dialog(const ABAgreeDialog());
      if (result == true) {
        setState(() {
          _selected = true;
        });
        final AuthorizationCredentialAppleID credential =
        await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
        );
        _appleToken = credential.identityToken ?? "";
        _login1();
      }
    }else{
      final AuthorizationCredentialAppleID credential =
      await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      _appleToken = credential.identityToken ?? "";
      _login1();
    }
  }

  ABElevateButton _buildAppleLogin() {
    return ABElevateButton(
        onPressed: _signApple,
        child: SizedBox(
            width: double.infinity,
            height: 50,
            child: Stack(alignment: Alignment.center, children: const [
              Align(
                  alignment: Alignment(-0.8, 0.0),
                  child: Icon(Icons.apple, size: 25, color: Colors.white)),
              Text('Sign in with Apple')
            ])));
  }

  OutlinedButton _buildFastLogin() {
    return OutlinedButton(
        onPressed: () {
          _appleToken = '';
          LogPvManger.stat(page: 'quicklogin');
          _login1();
        },
        style: OutlinedButton.styleFrom(
          minimumSize: const Size(200, 50),
          maximumSize: Size(Get.width - 80, 50),
        ),
        child: SizedBox(
          width: double.infinity,
          child: Stack(
            children: [
              Align(
                  alignment: const Alignment(-0.8, 0.0),
                  child: Image.asset('images/ceramics_35.webp', width: 25)),
              const Center(child: Text('Fast Login'))
            ],
          ),
        ));
  }

  Row _buildBottomTP() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
            onPressed: () {
              setState(() {
                _selected = !_selected;
              });
            },
            icon: _selected
                ? const Icon(Icons.check_circle)
                : const Icon(Icons.radio_button_unchecked),
            color: ABStyles.darkPink),
        _buildTermsAndPrivacy(),
      ],
    );
  }

  Widget _buildTermsAndPrivacy() {
    //By continuing, you agree to our Terms of Use and Privacy Policy
    return RichText(
        textAlign: TextAlign.center,
        text: TextSpan(
            text: "By using our App you agree with our\n",
            style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: ABStyles.darkBlack),
            children: [
              TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.to(() => const ABWebViewPage(
                          url: ABURLs.termsOfServiceURL,
                          title: 'Terms of Use'));
                    },
                  text: "Terms of Use",
                  style: const TextStyle(color: ABStyles.darkPink)),
              const TextSpan(text: " and "),
              TextSpan(
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.to(() => const ABWebViewPage(
                          url: ABURLs.privacyPolicyURL,
                          title: 'Privacy Policy'));
                    },
                  text: "Privacy Policy",
                  style: const TextStyle(color: ABStyles.darkPink)),
            ]));
  }
}
